<template>
	<a-modal
		:footer="null"
		:visible="visible"
		:title="title"
		@ok="handleOk"
		:maskClosable="false"
		@cancel="handleCancel"
	>
		<a-form
			ref="formRef"
			name="custom-validation"
			:model="formState"
			:rules="rules"
			v-bind="layout"
			@finish="handleFinish"
			@validate="handleValidate"
			@finishFailed="handleFinishFailed"
		>
			<a-form-item has-feedback label="菜单名称" name="name">
				 
				<a-input
					v-model:value="formState.name"
					allowClear
					placeholder="请输入菜单名称"
					autocomplete="off"
				/>
			</a-form-item>
            <a-form-item has-feedback label="模块" name="menu_type">
			 
			  <a-select v-model:value="formState.menu_type" placeholder="请选择模块">
                <a-select-option value="1" >模块</a-select-option>
                <a-select-option value="2" >菜单</a-select-option>
			   <a-select-option value="3" >操作</a-select-option>
			  </a-select>
			</a-form-item>
			     <a-form-item has-feedback label="上级菜单" name="pid">
			 
			  	 <a-tree-select
					v-model:value="formState.pid"
					show-search
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择上级菜单"
					allow-clear
					:replaceFields="replaceFields"
					tree-default-expand-all
				    :tree-data="adminMenu"
					@change="changeMenu"
				>
					   <template #title="{ value: val, title }">
						<b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
						<template v-else>{{ title }}</template>
						</template>
					</a-tree-select>
				</a-form-item>
			<a-form-item has-feedback label="后台路由地址" name="url">
				 
				<a-input
					v-model:value="formState.url"
					placeholder="请输入后台路由地址"
						allowClear
					autocomplete="off"
				/>
			</a-form-item>
			<a-form-item has-feedback label="图标" name="icon">
				 
				<a-input
					v-model:value="formState.icon"
				
					placeholder="请输入图标"
					autocomplete="off"
				>
				  <template #suffix>
					
						<a-tooltip slot="suffix" title="点击查看更多图标">
								<a href="https://fontawesome.dashgame.com/" target="_blank">
								  <i class="fa fa-align-left" :class="formState.icon?`fa-${formState.icon} ${formState.icon}`:`fa-align-left`"></i>
								</a> 
						</a-tooltip>
				</template>
				</a-input>
			 
			 
			 
			</a-form-item>
			<a-form-item has-feedback label="排序" name="sort">
				 
				<a-input
					v-model:value="formState.sort"
					allowClear
					placeholder="请输入排序值"
					autocomplete="off"
				/>
			</a-form-item>
			<a-form-item has-feedback label="状态" name="status">
				<a-select v-model:value="formState.status" placeholder="请选择状态">
			  <a-select-option value="1" >启用</a-select-option>
                <a-select-option value="0">禁用</a-select-option>
				</a-select>  
			</a-form-item>
			<a-form-item :wrapper-col="{ span: 14, offset: 4 }" style="text-align:center">
				<a-space>
					<a-button type="primary" html-type="submit">保存</a-button>
				<a-button  @click="resetForm">重置</a-button>
				</a-space>
			</a-form-item>
		</a-form>
	</a-modal>
</template>
<script>
import {
	defineComponent,
	reactive,
	ref,
	onMounted,
	nextTick,
	computed,
	getCurrentInstance
} from 'vue'
import { useStore, mapGetters } from 'vuex'
import { addMenulest ,updateMenuById} from '/@/api/app.js'
function arrToTree(arr, pid = null) {
	const res = []
	arr.forEach((item) => {
		if (item.pid === pid) {
			// 这样每次都需要遍历整个数组，因此时间复杂度为 n*n
			// const children = arrToTree(arr, item.id)

			// 往下递归时，每次数组的大小都在减小，每次都筛选掉父代元素，最终的时间复杂度为 n*logn
			const children = arrToTree(
				arr.filter((v) => v.pid !== pid),
				item.id
			)
			if (children.length) {
				res.push({ ...item, children })
			} else {
				res.push({ ...item })
			}
		}
	})
	return res
}
export default defineComponent({
	props: {
		model: {
			type: Object,
			default: function () {
				return {}
			}
		},
		title: {
			type: String,
			default: ''
		},
		visible: {
			type: Boolean,
			default: function () {
				return false
			}
		},
		cid: null
	},
	emits: {
		'close-modal': null,
		ok: null
	},
	setup(props, context) {
		const value = ref("123");
		const formRef = ref()
		const store = useStore()
		const formState = reactive({
		    sort:0,
			status: '1',
			icon: 'align-left'
		})
			 const replaceFields = ref({
			children: 'children',
			title: 'name',
			key: 'id',
			value:"id"
		})
		const adminMenu = ref([])
		const adminRoles = computed(
			mapGetters(['adminRoles']).adminRoles.bind({ $store: store })
		)
		const adminInfoList = computed(
			mapGetters(['adminInfo']).adminInfo.bind({ $store: store })
		)
		let checkAge = async (_rule, value) => {
			if (!value) {
				return Promise.reject('Please input the age')
			}

			if (!Number.isInteger(value)) {
				return Promise.reject('Please input digits')
			} else {
				if (value < 18) {
					return Promise.reject('Age must be greater than 18')
				} else {
					return Promise.resolve()
				}
			}
		}

	 let validatePid = async (_rule, value) => {
		 return Promise.resolve()
			// if (value == '' || value == undefined) {
			// 	return Promise.reject('请选择上级菜单')
			// } else {
			
			// 	return Promise.resolve()
			// }
		}

		const rules = {
			name: [
				{
					required: true,
					message: '请输入菜单名称',
					trigger: 'change'
				}
			],
			role_id: [
				{
					required: true,
					message: '请选择角色',
					trigger: 'change'
				}
			],
			menu_type: [
				{
					required: true,
					message: '请选择模块',
					trigger: 'change'
				}
			],
			url: [
				{
					required: true,
					message: '请输入后台路由地址',
					trigger: 'change'
				}
			],
			icon: [
				{
					required: false,
					message: '请输入图标',
					trigger: 'change'
				}
			],
			pid: [{ required: false, validator: validatePid, trigger: 'change' }],
			sort: [{ required: false, validator: validatePid, trigger: 'change' }],
			status: [
				{
					required: true,
					message: '请选择状态',
					trigger: 'change'
				}
			]
		}
		const layout = {
			labelCol: {
				span: 6
			},
			wrapperCol: {
				span: 14
			}
		}

		const handleFinish = (values) => {
		 
			context.emit('ok', {
				values,
				model: props.model
			})
		}

		const handleFinishFailed = (errors) => {
			console.log(errors)
		}

		const resetForm = () => {
			formRef.value.resetFields()
		}

		const handleValidate = (...args) => {
			console.log(args)
		}
		const handleCancel = () => {
			context.emit('close-modal', false)
		}
		const handleOk = () => {}
		onMounted(() => {
			const { edit } = props.model
			if (edit) {
				const { id, status, username, role_id } = adminInfoList.value
				formState.status = status + ''
				formState.username = username
				formState.role_id = role_id + ''
			}
		})
		const changeMenu=(value, label, extra)=>{
            console.log(formState.pid)
		}
		onMounted(() => {
			const {id,edit} = props.model;
			addMenulest()
				.then((res) => {
					const {
						result: { list }
					} = res
					adminMenu.value = arrToTree(list, 0)
				})
				.catch(() => {})
			if(edit){
				updateMenuById(id).then((res) => {
					const {
						result: { info:{
                         icon,
						id,
						menu_type,
						name,
						pid,
						sort,
						status,
						url,
						} }
					} = res
					formState.icon=icon;
					formState.menu_type=menu_type+'';
					formState.status=status+'';
					formState.name=name;
					formState.pid=(pid*1)!=0?pid:'';
					formState.sort=sort;
					formState.url=url;
				})
				.catch(() => {})
			}
		})
		return {
			formState,
			formRef,
			rules,
			layout,
			adminRoles,
			adminInfoList,
			handleFinishFailed,
			handleFinish,
			resetForm,
			handleValidate,
			handleCancel,
			handleOk,
			adminMenu,
			replaceFields,
			changeMenu,
			value
		}
	}
})
</script>